# -*- coding:UTF-8 -*-
from django.shortcuts import render
from django.http import JsonResponse
from django.forms.models import model_to_dict
from cmdb.views import *
import json
from diy_decorator.auth import *

from cmdb.base_database import *

from equipment_database.equipment_info_class import *
from equipment_database.server_room_info_class import *
from equipment_database.system_info_class import *
from equipment_database.network_card_info_class import *
from equipment_database.belong_sys_info_class import *
from equipment_database.merchant_info_class import *
from equipment_database.room_no_info_class import *
from equipment_database.business_server_mapping_class import *
from equipment_database.network_info_class import *
from equipment_database.equipment_maint_log_class import *
from saltstack.salt_database.node_list_class import update_salt_node

from cmdb.mbusiness.business_database.business_info_class import filter_business_info

#服务器列表
@login_required()
def index(request):
    
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    serverRoomId = int(request.GET.get('server_room_id',0))
    equipmentType = int(request.GET.get('equipment_type',0))

    searchStr = request.GET.get('search','')
    searchStr = searchStr.strip()
    #获取服务器列表
    searchRes = equipment_info(startpage,endpage,serverRoomId,equipmentType,searchStr)
    count = searchRes['count']
    equipmentRes = searchRes['equipment_info_list']

    page_total = int(count/page_num)
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1
    for equipment in equipmentRes:
        equipment.equipment_type_value =  equipmentTypeDict[equipment.equipment_type]
    #获取机房列表
    serverRoomInfo = get_server_rooms()
    serverRoomDict = {}
    for singleRoom in serverRoomInfo:
        serverRoomDict[singleRoom['id']] = singleRoom['server_room']
    for singleEquipment in equipmentRes:
        singleEquipment.server_room = serverRoomDict[singleEquipment.server_room_id]

    context={
        "equipment_list" : equipmentRes,
        'server_room_list' : serverRoomInfo,
        'equipment_type_list' : equipmentTypeDict,
        'equipment_type' : equipmentType,
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count,
        'search' : searchStr,
        'server_room_id' : serverRoomId
    }
    return render(request, 'cmdb/mequipment/equipment.html', context)

#服务器新增页面
@login_required()
def addinfo(request):
    #商家信息
    merRes = get_merchant_infos()
    #机房信息
    sRoomRes = get_server_rooms()
    #房间号信息
    roomNoRes = get_room_no_infos()
    roomNoDict = {}
    for singleRoomNo in roomNoRes:
        if not roomNoDict.has_key(singleRoomNo.server_room_id):
            roomNoDict[singleRoomNo.server_room_id] = []
        roomNoDict[singleRoomNo.server_room_id].append(singleRoomNo)
    firstRoomInfo = {}
    serverRoomDict = {}
    for singleRoom in sRoomRes:
        if roomNoDict.has_key(singleRoom['id']):
            singleRoom['room_no_info'] = roomNoDict[singleRoom['id']]
        if not firstRoomInfo:
            firstRoomInfo = singleRoom
        serverRoomDict[singleRoom['id']] = singleRoom
    context = {
        'merchant_info' : merRes,
        'first_room_info' : firstRoomInfo,
        'server_room_list' : serverRoomDict,
        'use_status_list' : useStatusDict,
        'equipment_type_list' : equipmentTypeDict,
        'environment_list' : environmentDict,
        'physical_count' : 1
    }
    return render(request, 'cmdb/mequipment/equipment_add.html', context)

#服务器新增
def addaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    eType = request.POST.get('equipment_type')
    equipmentModel = request.POST.get('equipment_model')
    cpuModel = request.POST.get('cpu_model')
    hostname = request.POST.get('hostname')
    innerip = request.POST.get('sys_ip_inner')
    networkCardInfo = request.POST.get('network_card_info')
    netCardDecodeJson = json.loads(networkCardInfo)
    outerip = request.POST.get('sys_ip_outer')
    seriesNo = request.POST.get('serial_num')
    assetNumber = request.POST.get('asset_number')
    cpu = request.POST.get('cpu')
    memory = request.POST.get('memory')
    harddisk = request.POST.get('harddisk')
    environment = request.POST.get('environment')
    serverRoomId = request.POST.get('server_room_id')
    roomNoId = request.POST.get('room_no_id')
    cabinet = request.POST.get('cabinet')
    idrac = request.POST.get('idrac')
    uStartPos = request.POST.get('start_cabinet')
    uEndPos = request.POST.get('end_cabinet')
    uNum = abs(int(uEndPos)-int(uStartPos))
    startTime = request.POST.get('start_time')
    maintEndTime = request.POST.get('maint_end_time')
    manufacturerId = request.POST.get('manufacturer_id')
    providerId = request.POST.get('provider_id')
    responser = request.POST.get('responser')
    comment1 = request.POST.get('comment1')
    sysVersion = request.POST.get('system_ver')
    coreVersion = request.POST.get('core_ver')
    parentIp = request.POST.get('sys_parent_ip')
    useStatus = request.POST.get('use_status')
    belong_sys_list = request.POST.get('belong_sys_list')
    belong_sys_arr = belong_sys_list.split(',')
    comment2 = request.POST.get('comment2')
    operator = request.POST.get('operator')
    response_dict = {"status":1}
    set_transaction(False)
    try:
        cursor = get_cursor()
        #获取最大编号
        equipment_no = get_max_equipment_no(cursor)
        #添加设备配置
        add_equipment_info(equipment_no, eType, equipmentModel, hostname, seriesNo, assetNumber, cpuModel,
                           cpu, memory, harddisk, innerip, outerip, environment, serverRoomId, roomNoId,
                           cabinet, idrac, uNum, uStartPos, uEndPos, startTime, maintEndTime, manufacturerId,
                           providerId, comment1, operator, responser, cursor)
        #添加系统配置
        add_system_info(equipment_no, sysVersion, coreVersion, parentIp, useStatus, comment2, operator, cursor)
        #删除网卡信息，重新插入
        del_network_card_info(equipment_no, cursor)
        if netCardDecodeJson:
            itemDict = {}
            for singleCard in netCardDecodeJson:
                sConfigureArr = singleCard.split(";")
                for sConfigure in sConfigureArr:
                    print sConfigure
                    itemArr = sConfigure.split("#")
                    if itemArr[1] == 'undefined':
                        itemArr[1] = ''
                    itemDict[itemArr[0]] = itemArr[1]
                add_network_card_info(equipment_no, itemDict['card_name'], itemDict['mac'], cursor)
        del_belong_sys_info(equipment_no, cursor)
        if belong_sys_arr:
            for belong_sys_single in belong_sys_arr:
                if belong_sys_single != '':
                    add_belong_sys_info(equipment_no, belong_sys_single, operator, cursor)
        #更新salt node状态为已上报
        update_salt_node(hostname, '1', cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
        print Exception,":",ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#服务器编辑页面
@login_required()
def editinfo(request):

    eNo = request.GET.get('equipment_no')
    context = {
        'page' : request.GET.get('page')
    }

    try:
        equipmentRes = get_equipment_info(eNo)
        sysRes = get_system_info(eNo)
        equipmentRes.system_ver = sysRes.system_ver
        equipmentRes.core_ver = sysRes.core_ver
        equipmentRes.sys_parent_ip = sysRes.sys_parent_ip
        equipmentRes.use_status = sysRes.use_status
        equipmentRes.comment2 = sysRes.comment
        equipmentRes.network_card_list = {}
        netIdx = 0
        netCardRes = get_network_card_info(eNo)
        equipmentRes.network_card_first = {}
        if netCardRes:
            for singleCard in netCardRes:
                if netIdx == 0:
                    equipmentRes.network_card_first = singleCard
                else:
                    equipmentRes.network_card_list[netIdx] = singleCard
                netIdx += 1
        equipmentRes.network_card_count = netIdx
        equipmentRes.belong_sys_list = {}
        blRes = filter_belong_sys_info(eNo)
        idx = 0
        equipmentRes.belong_sys_first = ''
        if blRes:
            for singeR in blRes:
                if idx == 0:
                    equipmentRes.belong_sys_first = singeR.belong_sys_name
                else:
                    equipmentRes.belong_sys_list["belongSys" + str(idx)] = {
                        'delid' : 'btnDel' + str(idx),
                        'belong_sys_name':singeR.belong_sys_name
                    }
                idx += 1
        equipmentRes.belong_sys_count = idx
        #server room
        context['server_room_list'] = get_server_rooms()
        context['room_no_info'] = get_room_no_infos()
        context['equipment_info'] = equipmentRes
        context['merchant_info'] = get_merchant_infos()

    except Exception,ex:
        print Exception,":",ex
    context['use_status_list'] = useStatusDict
    context['environment_list'] = environmentDict
    context['equipment_type_list'] = equipmentTypeDict
    return render(request, 'cmdb/mequipment/equipment_edit.html', context)

#服务器编辑
def editaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    eNo = request.POST.get('equipment_no')
    response_dict = {"status":1}
    networkCardInfo = request.POST.get('network_card_info')
    netCardDecodeJson = json.loads(networkCardInfo)
    belong_sys_list = request.POST.get('belong_sys_list')
    belong_sys_arr = belong_sys_list.split(',')
    uStartPos = request.POST.get('start_cabinet')
    uEndPos = request.POST.get('end_cabinet')
    uNum = abs(int(uEndPos)-int(uStartPos))
    operator = request.POST.get('operator')

    set_transaction(False)
    try:
        cursor = get_cursor()
        edit_equipment_info(eNo, request.POST.get('equipment_type'), request.POST.get('equipment_model'), request.POST.get('hostname'),
                            request.POST.get('serial_num'), request.POST.get('asset_number'), request.POST.get('cpu_model'),
                            request.POST.get('cpu'), request.POST.get('memory'), request.POST.get('harddisk'), request.POST.get('sys_ip_inner'),
                            request.POST.get('sys_ip_outer'), request.POST.get('environment'), request.POST.get('server_room_id'), request.POST.get('room_no_id'),
                            request.POST.get('cabinet'), request.POST.get('idrac'), uNum, uStartPos, uEndPos, request.POST.get('start_time'), request.POST.get('maint_end_time'),
                            request.POST.get('manufacturer_id'),request.POST.get('provider_id'), request.POST.get('comment1'), operator, request.POST.get('responser'), cursor)
        update_system_info(eNo, request.POST.get('system_ver'), request.POST.get('core_ver'), request.POST.get('sys_parent_ip'),
                           request.POST.get('use_status'), request.POST.get('comment2'), operator, cursor)
        del_network_card_info(eNo, cursor)
        if netCardDecodeJson:
            itemDict = {}
            for singleCard in netCardDecodeJson:
                sConfigureArr = singleCard.split(";")
                for sConfigure in sConfigureArr:
                    itemArr = sConfigure.split("#")
                    if itemArr[1] == 'undefined':
                        itemArr[1] = ''
                    itemDict[itemArr[0]] = itemArr[1]
                add_network_card_info(eNo, itemDict['card_name'], itemDict['mac'], cursor)
        del_belong_sys_info(eNo, cursor)
        if belong_sys_arr:
            for belong_sys_single in belong_sys_arr:
                if belong_sys_single != '':
                    add_belong_sys_info(eNo, belong_sys_single, operator, cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
        print Exception,":",ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#获取服务器详情信息
def getaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'data' : {}}
    eNo = request.POST.get('eNo')
    try:
        eInfo = get_equipment_info(eNo)
        mRes = get_merchant_info(eInfo.manufacturer_id)
        response_dict['data']['manufacturer'] = mRes.factory_name
        response_dict['data']['provider'] = mRes.factory_name
        if eInfo.manufacturer_id != eInfo.provider_id:
            mpRes = get_merchant_info(eInfo.provider_id)
            response_dict['data']['provider'] = mpRes.factory_name
        serverRoomInfo = get_server_room(eInfo.server_room_id)
        response_dict['data']['server_room'] = serverRoomInfo.server_room
        if exists_room_no(eInfo.room_no_id):
            roomNoInfo = get_room_no(eInfo.room_no_id)
            response_dict['data']['room_no'] = roomNoInfo.room_no
        else:
            response_dict['data']['room_no'] = ''
        netCardInfo = get_network_card_info(eNo)
        response_dict['data']['network_card_info'] = []
        if netCardInfo:
            for singleCard in netCardInfo:
                response_dict['data']['network_card_info'].append(model_to_dict(singleCard, exclude=['is_active', 'is_stuff']))
        sInfo = get_system_info(eNo)
        bInfo = filter_belong_sys_info(eNo)
        bmInfo = filter_server_mapping_no(eNo)
        equipmentInfo = model_to_dict(eInfo, exclude=['is_active', 'is_stuff'])
        equipmentInfo['equipment_type_name'] = equipmentTypeDict[equipmentInfo['equipment_type']]
        equipmentInfo['environment_desc'] = environmentDict[equipmentInfo['environment']]
        response_dict['data']['equipment_info']  = equipmentInfo
        response_dict['data']['system_info']  = model_to_dict(sInfo, exclude=['is_active', 'is_stuff'])
        response_dict['data']['system_info']['use_status_desc'] = useStatusDict[response_dict['data']['system_info']['use_status']]
        if bInfo:
            response_dict['data']['belong_system_list'] = []
            for singleInfo in bInfo:
                response_dict['data']['belong_system_list'].append(model_to_dict(singleInfo, exclude=['is_active', 'is_stuff']))
        if bmInfo:
            response_dict['data']['business_server_mapping_list'] = []
            for singleInfo in bmInfo:
                mappingArr = model_to_dict(singleInfo, exclude=['is_active', 'is_stuff'])
                businessInfo = filter_business_info(singleInfo.module_no)
                mappingArr['module_name'] = businessInfo.module_name
                mappingArr['use_status_desc'] = moduleStatusDict[mappingArr['use_status']]
                response_dict['data']['business_server_mapping_list'].append(mappingArr)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
        print Exception,":",ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#删除服务器
def deleteaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    eNo = request.POST.get('eNo')
    equipmentInfo = get_equipment_info(eNo)
    set_transaction(False)
    try:
        cursor = get_cursor()
        mappingNum = server_mapping_no_count(eNo, cursor)
        if mappingNum > 0:
            response_dict['status'] = 0
            response_dict['message'] = '存在挂载模块，不可删除'
        else:
            del_equipment_info(eNo, cursor)
            del_system_info(eNo, cursor)
            del_belong_sys_info(eNo, cursor)
            update_salt_node(equipmentInfo.hostname, '0', cursor)
            connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#网络设备列表
@login_required()
def netinfo(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    serverRoomId = int(request.GET.get('server_room_id','0'))
    searchStr = request.GET.get('search','')
    startpage=(page-1)*page_num
    endpage=startpage+page_num

    networkInfo = network_info(startpage,endpage,serverRoomId,searchStr)
    count = networkInfo['count']
    netRes = networkInfo['network_info_list']
    serverRoomRes = get_server_rooms()
    serverRoomDict = {}
    for singleRoom in serverRoomRes:
        serverRoomDict[singleRoom['id']] = singleRoom['server_room']
    for singleNet in netRes:
        singleNet.server_room = serverRoomDict[singleNet.server_room_id]

    page_total = int(count/page_num)
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1

    context={
        "network_list" : netRes,
        'server_room_list' : serverRoomRes,
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count,
        'search' : searchStr,
        'server_room_id' : serverRoomId
    }
    return render(request, 'cmdb/mequipment/net.html', context)

#网络设备新增页面
@login_required()
def netaddinfo(request):
    context = {}
    try:
        merRes = get_server_rooms()
        context['server_room_list'] = merRes
    except Exception,ex:
        print Exception,":",ex
    return render(request, 'cmdb/mequipment/net_add.html', context)

#网络设备新增
def netaddaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    equipment_no = 'NE00001'
    equipmentModel = request.POST.get('equipmentModel')
    eqType = request.POST.get('eqType')
    version = request.POST.get('version')
    hostname = request.POST.get('hostname')
    manageIp = request.POST.get('manageIp')
    assetNumber = request.POST.get('asset_number')
    serverRoom = request.POST.get('serverRoom')
    cabinet = request.POST.get('cabinet')
    uStartPos = request.POST.get('uStartPos')
    uEndPos = request.POST.get('uEndPos')
    seriesNo = request.POST.get('seriesNo')
    purchaseTime = request.POST.get('purchaseTime')
    maintEndTime = request.POST.get('maintEndTime')
    comment = request.POST.get('comment')
    operator = request.POST.get('operator')
    try:
        eqNum=NetworkInfo.objects.count()
        if eqNum > 0:
            netNoRes=NetworkInfo.objects.latest('equipment_no')
            if netNoRes:
                tmpNo=str(int(netNoRes.equipment_no[2:]) + 1)
                equipment_no = 'NE' + string.rjust(tmpNo,5,'0')
        add_network_info(equipment_no, equipmentModel, eqType, version,hostname, manageIp,assetNumber,serverRoom, cabinet,
                         uStartPos, uEndPos,seriesNo,purchaseTime,maintEndTime,comment, operator)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = '执行异常，请联系管理员'
        print Exception,":",ex

    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#网络设备编辑页面
@login_required()
def neteditinfo(request):
    context = {
        'page' : request.GET.get('page')
    }
    eNo = request.GET.get('eno')
    try:
        context['network_info'] = get_network_info(eNo)
        context['server_room_list'] = get_server_rooms()
    except Exception,ex:
        print Exception,":",ex
    return render(request, 'cmdb/mequipment/net_edit.html', context)

#网络设备编辑
def neteditaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    eNo = request.POST.get('eNo')
    response_dict = {'status':1,'message':''}
    try:
        edit_network_info(eNo, request.POST.get('equipmentModel'), request.POST.get('eqType'), request.POST.get('version'),
                     request.POST.get('hostname'), request.POST.get('manageIp'),request.POST.get('asset_number'),
                     request.POST.get('serverRoom'), request.POST.get('cabinet'), request.POST.get('uStartPos'),
                     request.POST.get('uEndPos'),request.POST.get('seriesNo'),request.POST.get('purchaseTime'),
                     request.POST.get('maintEndTime'),request.POST.get('comment'), request.POST.get('operator'))
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#网络设备删除
def netdelete(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    eNo = request.POST.get('eNo')
    try:
        del_network_info(eNo)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#获取网络设备详情信息
def netget(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    eNo = request.POST.get('eNo')
    netInfo = get_network_info(eNo)
    merRes = get_server_room(netInfo.server_room_id)
    netArr = model_to_dict(netInfo, exclude=['is_active', 'is_stuff'])
    netArr['server_room'] = merRes.server_room
    response_dict['data'] = netArr
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#机房列表信息
@login_required()
def roominfo(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    roomInfo = server_room_info(startpage,endpage)
    count = roomInfo['count']
    page_total = int(count/page_num)
    if (count % page_num) > 0 or page_total == 0:
        page_total += 1
    context={
        "server_room_list" : roomInfo['server_room_info_list'],
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count
    }
    return render(request, 'cmdb/mequipment/server_room.html', context)

#机房添加页面
@login_required()
def saddinfo(request):
    return render(request, 'cmdb/mequipment/serverroom_add.html', {})

#机房添加
def saddaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    server_room = request.POST.get('server_room')
    room_no_list = request.POST.get('room_no_info_list')
    roomNoDecodeJson = json.loads(room_no_list)
    phone = request.POST.get('phone')
    server_room_addr = request.POST.get('server_room_addr')
    comment = request.POST.get('comment')
    operator = request.POST.get('operator')
    set_transaction(False)
    try:
        cursor = get_cursor()
        id = add_server_room(server_room, phone, server_room_addr, comment, operator, cursor)
        del_room_no_info(str(id), cursor)
        if roomNoDecodeJson:
            for single_room in roomNoDecodeJson:
                add_room_no_info(single_room, str(id), cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
        print  Exception,":",ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#机房编辑页面
@login_required()
def seditinfo(request):
    id = request.GET.get('id')
    sInfo = get_server_room(id)
    roomNoInfo = filter_room_no(id)
    sInfo.first_room_no = ''
    sInfo.room_no_list = {}
    idx = 0
    if roomNoInfo:
        for singleRoom in roomNoInfo:
            if idx == 0:
                sInfo.first_room_no = singleRoom.room_no
            else:
                sInfo.room_no_list[idx] = singleRoom.room_no
            idx += 1
    context={
        'page' : request.GET.get('page'),
        'server_room_info' : sInfo,
        'room_count' : idx
    }
    return render(request, 'cmdb/mequipment/serverroom_edit.html', context)

#机房编辑
def seditaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    id = request.POST.get('id')
    room_no_list = request.POST.get('room_no_info_list')
    roomNoDecodeJson = json.loads(room_no_list)
    response_dict = {'status':1,'message':''}
    set_transaction(False)
    try:
        cursor = connection.cursor()
        update_server_room(id, request.POST.get('server_room'), request.POST.get('phone'), request.POST.get('server_room_addr'),
                           request.POST.get('comment'),  request.POST.get('operator'), cursor)
        del_room_no_info(id, cursor)
        if roomNoDecodeJson:
            for single_room in roomNoDecodeJson:
                add_room_no_info(single_room, id, cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#机房删除
def sdeleteaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    id = request.POST.get('id')
    set_transaction(False)
    try:
        cursor = get_cursor()
        del_server_room(id, cursor)
        del_room_no_info(id, cursor)
        connection.commit()
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#商家信息列表
@login_required()
def merchantinfo(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage = (page-1)*page_num
    endpage = startpage+page_num

    merchantInfo = merchant_info(startpage,endpage)
    count = merchantInfo['count']
    sRes = merchantInfo['merchant_info_list']

    page_total = int(count/page_num)
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1

    context={
        "merchant_list" : sRes,
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count
    }
    return render(request, 'cmdb/mequipment/provider.html', context)

#商家添加页面
@login_required()
def maddinfo(request):
    return render(request, 'cmdb/mequipment/provider_add.html', {})

#商家添加
def maddaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    factory_name = request.POST.get('factory_name')
    contacts = request.POST.get('contacts')
    contact_way = request.POST.get('contact_way')
    comment = request.POST.get('comment')
    operator = request.POST.get('operator')
    try:
        add_merchant_info(factory_name, contacts, contact_way, comment, operator)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
        print  Exception,":",ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#商家编辑页面
@login_required()
def meditinfo(request):
    context={
        'page' : request.GET.get('page')
    }
    id=request.GET.get('id')
    try:
        mInfo = get_merchant_info(id)
        context['merchant_info'] = mInfo
    except Exception,ex:
        print Exception,":",ex
    return render(request, 'cmdb/mequipment/provider_edit.html', context)

#商家编辑
def meditaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    id=request.POST.get('id')
    try:
        edit_merchant_info(id, request.POST.get('factory_name'), request.POST.get('contacts'), request.POST.get('contact_way'),
                           request.POST.get('comment'), request.POST.get('operator'))
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#商家删除
def mdelete(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    id=request.POST.get('id')
    try:
        del_merchant_info(id)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#设备维修记录列表
@login_required()
def repairinfo(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    maintInfo = equipment_maint_log(startpage,endpage)

    count = maintInfo['count']
    eRes = maintInfo['equipment_maint_log_list']

    page_total = int(count/page_num)
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1

    context={
        "equipment_maint_list" : eRes,
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count
    }
    return render(request, 'cmdb/mequipment/maintain_log.html', context)

#设备维修记录添加页面
@login_required()
def raddinfo(request):
    return render(request, 'cmdb/mequipment/maintain_add.html', {})

#设备维修记录添加
def raddaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    try:
        add_equipment_maint_log(request.POST.get("serial_num"),request.POST.get("maint_time"),request.POST.get("maint_man"),
                                request.POST.get("problem"),request.POST.get("repair_time"),request.POST.get("present"),
                                request.POST.get("pepair_man"),request.POST.get("resolution"),request.POST.get("comment"),
                                request.POST.get("operator"))
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#设备维修记录编辑页面
@login_required()
def reditinfo(request):
    context = {
        'page' : request.GET.get('page')
    }
    id=request.GET.get('id')
    try:
        rInfo = get_equipment_maint_log(id)
        context['equipment_maint_log'] = rInfo
    except Exception,ex:
        print Exception,ex
    return render(request, 'cmdb/mequipment/maintain_edit.html', context)

#设备维修记录编辑
def reditaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    id=request.POST.get('id')
    try:
        edit_equipment_maint_log(id,request.POST.get('maint_time'),request.POST.get('maint_man'),request.POST.get('problem'),
                                 request.POST.get('repair_time'),request.POST.get('present'),request.POST.get('pepair_man'),
                                 request.POST.get('resolution'),request.POST.get('comment'),request.POST.get('operator'))
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#设备维修记录详情
def rgetaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    id=request.POST.get('id')
    try:
        eInfo = get_equipment_maint_log(id)
        response_dict['data'] = model_to_dict(eInfo, exclude=['is_active', 'is_stuff'])
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

def eqUniqueCheck(request):
    ip = request.POST.get('sys_ip_inner', '')
    hostname = request.POST.get('hostname', '')
    id = request.POST.get('id', '')
    response_dict = {'status' : 1}
    if ip != '' or hostname != '':
        try:
            check = True
            if ip != '':
                if id == '':
                    check = exist_ip_equipment_info(ip)
                else:
                    check = exclude_ip_equipment_info(ip,id)
            else:
                if id == '':
                    check = filter_host_equipment_info(hostname)
                else:
                    check = exclude_host_equipment_info(hostname, id)
            response_dict['data'] = check
        except Exception,ex:
            response_dict['status'] = 0
            response_dict['message'] = '查询失败'
            print Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

def netUniqueCheck(request):
    response_dict = {'status' : 1}
    serial_num = request.POST.get('serial_num', '')
    id = request.POST.get('id', '')
    if serial_num != '':
        try:
            check = True
            if id == '':
                check = exist_serial_network_info(serial_num)
            else:
                check = exclude_serial_network_info(serial_num, id)
            response_dict['data'] = check
        except Exception,ex:
            response_dict['status'] = 0
            response_dict['message'] = '查询失败'
            print Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response
